angular.module('mamApp').controller('mainController', ['$scope', '$rootScope', '$state', 'InitManger', function ($scope, $rootScope, $state, InitManger) {

    $scope.$state = $state;
    $scope.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    $scope.messageIsShow = true;
    $scope.side={close:false};
    

    $rootScope.$on('$stateChangeSuccess',
        function (event, toState, toParams, fromState, fromParams) {
                document.body.scrollTop=0;

            clearInterval($rootScope.timerProgress);
            InitManger.menuItem().then(function (result) {
                $scope.meunItems = result.admin;

                $scope.meunItems.forEach(function (meun) {
                    meun.items.forEach(function (item1) {
                        if (toState.name.indexOf(item1['sref']) > -1) {
                            $scope.menuSelect = meun;

                        } else {
                            item1.items.forEach(function (item) {
                                if (toState.name.indexOf(item['sref']) > -1) {
                                    $scope.menuSelect = meun;
                                }

                            })
                        }
                    })
                })
            })

        })

    $scope.backHome=function(){
        $state.go('main.home',{},{reload:true});
        window.location.reload();
    }

    $scope.menuTitleClick = function (item) {
        if (item.sref) {
            $state.go(item.sref, {}, {inherit: false})
        }

    }

    $scope.menuClick = function (menu, index) {

        $scope.menuSelect = menu;

    }


    if (!localStorage.getItem("provinces")) {
        InitManger.provinces().then(function (result) {
            localStorage.setItem("provinces", JSON.stringify(result))
        })

        InitManger.cities().then(function (result) {
            localStorage.setItem("city", JSON.stringify(result))

        })

    }


    InitManger.codeTable().then(function (result) {
        localStorage.setItem("codeTable", JSON.stringify(result))
        $scope.table = JSON.parse(localStorage.getItem('codeTable'));

    })

    $scope.menuTitleClick = function (item) {
        if (item.sref) {
            $state.go(item.sref, {}, {inherit: false})
        }

    }


    $scope.signOut = function () {
        clearInterval($rootScope.timerProgress);
        $scope.userInfo.token="";

        localStorage.setItem("userInfo", JSON.stringify( $scope.userInfo))


        window.location = '#/login';

    };



}])

